<?php

namespace app\admin\controller\oa;

use app\common\controller\Backend;
use think\Db;
use think\Env;
use think\exception\ValidateException;

/**
 * 日志
 *
 * @icon fa fa-table
 * @remark 当一个页面上存在多个Bootstrap-table时该如何控制按钮和表格
 */
class Log extends Backend
{
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];
    protected $relationSearch = true;

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;
    protected $categorylist = [];
    private $redis;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Log;
        $this->redis = redis(Env::get('redis.host'), Env::get('redis.port'), Env::get('redis.pwd'), Env::get('redis.db'));

        $admin_arr = Db::table('fa_admin')
            ->field('id,nickname')
            ->where('status','normal')
            ->where('id','<>',$this->auth->id)
            ->select();
        $this->view->assign("arr", $admin_arr);
    }

    /**
     * 查看
     */
    public function index()
    {

        if (isset(request()->param()['is'])){
            $is = request()->param()['is'];
        }else{
            $is =2;
        }
        $this->view->assign("is", $is);
        return $this->view->fetch();
    }

    public function table1()
    {
        $this->model = model('Log');
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with([
                    'admin' => function ($query) {
                        $query->withField('id,nickname,avatar');
                    }
                ])
                ->where($where)
                ->where('admin_id',$this->auth->id)
                ->order('id', 'desc')
                ->paginate($limit);

            if (!empty($list->items())){
                foreach ($list->items() as $k=>$v){
                    $list->items()[$k]['name'] = $v->admin['nickname'].'的日志';
                }
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch('index');
    }

    public function table2()
    {
        $this->model = model('Relation');
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with([
                    'log' => function ($query) {
                        $query->withField('id,admin_id,create_time');
                    }
                ])
                ->where($where)
                ->where('relation.admin_id',$this->auth->id)
                ->where('relation.status',1)
                ->order('id', 'desc')
                ->paginate($limit);

            if (!empty($list->items())){
                foreach ($list->items() as $k=>$v){
                    $name = Db::table('fa_admin')
                        ->field('id,nickname,avatar')
                        ->where('id',$v->log['admin_id'])
                        ->find();
                    $list->items()[$k]['name'] = $name['nickname'].'的日志';
                    $list->items()[$k]['avatar'] = $name['avatar'];
                }
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch('index');
    }


    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }

                $params['admin_id'] = $this->auth->id;
                $ids_arr = $params['ids'];
                unset($params['ids']);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }

                    $result = $this->model->allowField(true)->save($params);
                    $id = $this->model->id;//新增的id

                    $arr = [];
                    if (!empty($ids_arr)){
                        foreach ($ids_arr as $k=>$v){
                            $arr[$k] = [
                                'log_id' => $id,
                                'admin_id' => $v,
                                'create_time' => time(),
                                'is_comment' => 0,
                                'status' => 1,
                            ];
                        }

                        $insert = Db::table('fa_oa_relation')
                            ->insertAll($arr);
                    }else{
                        $insert = 1;
                    }
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if (($result !== false) && ($insert !== false)){
                    Db::commit();
                    $this->success();
                }else{
                    Db::rollback();
                    $this->error(__('失败'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {

        $ids = request()->param()['id'];
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);


                var_dump($params);die();
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $admin_arr = Db::table('fa_admin')
            ->field('nickname,avatar')
            ->where('id',$row->admin_id)
            ->find();

        if (empty($admin_arr)){
            $name = '';
            $avatar = '';
        }else{
            $name = $admin_arr['nickname'].'的日志';
            $avatar = $admin_arr['avatar'];
        }

        $w = date('w',$row->create_time);

        switch ($w){
            case 0:
                $ws = '星期天';
                break;
            case 1:
                $ws = '星期一';
                break;
            case 2:
                $ws = '星期二';
                break;
            case 3:
                $ws = '星期三';
                break;
            case 4:
                $ws = '星期四';
                break;
            case 5:
                $ws = '星期五';
                break;
            case 6:
                $ws = '星期六';
                break;
            default:
                $ws = '';
                break;
        }

        $time = date('Y-m-d',$row->create_time).' '.$ws;

        $rows = [
            'name' => $name,
            'time' => $time,
            'avatar' => $avatar,
        ];

        if ($row->admin_id == $this->auth->id){
            $is = 1;
        }else{
            $is = 2;
        }

        $pan_arr = Db::table('fa_oa_relation')
            ->where(['log_id'=>$row->id,'admin_id'=>$this->auth->id,'status'=>1])
            ->find();

        if (empty($pan_arr)){
            $pan = 1;
        }else{
            if ($pan_arr['is_comment'] == 1){
                $pan = 1;
            }else{
                $pan = 2;
            }
        }

        $row->image = explode(',',$row->images);


        $this->view->assign("rows", $rows);
        $this->view->assign("row", $row);
        $this->view->assign("is", $is);
        $this->view->assign("pan", $pan);
        //$this->view->assign("comment", $comment);
        return $this->view->fetch();
    }

    /**
     * 评论
     *
     */
    public function get_comment(){
        $arr = request()->param();
        //评论数据
        $comment = Db::table('fa_oa_comment')
            ->alias('a')
            ->field('a.id,b.nickname,b.avatar,a.create_time,a.msg')
            ->join('fa_admin b','a.admin_id=b.id','left')
            ->where('a.log_id',$arr['id'])
            ->order('id','desc')
            ->select();

        if (!empty($comment)){
            foreach ($comment as $k=>$v){
                $comment[$k]['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
            }
        }
        $this->success('成功','',$comment);

    }

    /**
     * 操作
     *
     */
    public function for(){
        $arr = request()->param();

        $pan_arr = Db::table('fa_oa_relation')
            ->where(['log_id'=>$arr['id'],'admin_id'=>$this->auth->id,'status'=>1])
            ->find();

        if (empty($pan_arr)){
            $this->error('关系数据为空');
        }

        if ($pan_arr['is_comment'] == 1){
            $this->error('已评论过，请勿重复评论');
        }


        //开启事务
        Db::startTrans();

        $insert = Db::table('fa_oa_comment')
            ->insertGetId([
                'admin_id' => $this->auth->id,
                'log_id' => $arr['id'],
                'msg' => $arr['msg'],
                'create_time' => time(),
            ]);

        $update = Db::table('fa_oa_relation')
            ->where('id',$pan_arr['id'])
            ->update([
                'is_comment' => 1,
                'update_time' => time(),
            ]);

        if (($insert !== false) && ($update !== false)){
            //事务提交
            Db::commit();
            $this->success('成功');
        }else{
            //事务回滚
            Db::rollback();
            $this->error('失败');
        }

    }

    public function list(){
        $result = Db::table('fa_admin')
            ->field('id,nickname')
            ->where('id','<>',$this->auth->id)
            ->select();

        foreach ($result as $key => $value) {
            $searchlist[] = ['id' => $value['id'], 'name' => $value['nickname']];
        }
        $data = ['searchlist' => $searchlist];
        $this->success('', null, $data);
    }

}
